<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="68px">
        <el-form-item label="工段">
          <el-select
            v-model="searchParam.workshopSectionId"
            placeholder="请选择工段"
            clearable
            filterable
            @change="changeWorkshopSection"
          >
            <el-option
              v-for="item in workshopSectionList"
              :key="item.id"
              :label="item.workshopSectionCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processCodeList"
              :key="item.processId"
              :label="item.processCode"
              :value="item.processId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线">
          <el-select
            v-model="searchParam.processEquipId"
            placeholder="请选择生产线"
            clearable
            filterable
            @change="processEquipChange"
          >
            <el-option
              v-for="item in processEquipList"
              :key="item.processEquipId"
              :label="item.processEquipCode"
              :value="item.processEquipId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            clearable
            filterable
            @change="equipChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.equipId"
              :label="item.equipName"
              :value="item.equipId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择客户"
            clearable
            filterable
            @change="changeProject"
          >
            <el-option
              v-for="item in projectList"
              :key="item.projectId"
              :label="`${item.projectName}`"
              :value="item.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select
            v-model="searchParam.productModel"
            placeholder="请选择产品"
            clearable
            filterable
            :filter-method="customFilter"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.productModel"
              :label="`${item.productModel}`"
              :value="item.productModel"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetHandle"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header v-if="authAllPerm(['psm:jkcs:add', 'psm:jkcs:import'])">
        <el-button
          v-hasPerm="['psm:jkcs:add']"
          type="success"
          plain
          @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['psm:jkcs:import']"
          type="success"
          @click="excelBoxOpen"
          >导入
        </el-button>
        <el-button
          :disabled="ids.length === 0"
          :loading="deleteLoading"
          @click="exportExcel"
          >导出
        </el-button>
        <el-button
          type="primary"
          plain
          :disabled="ids.length === 0"
          @click="batchEnable(1)"
          >批量启用</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="batchEnable(0)"
          >批量停用</el-button
        >
        <el-button
          type="primary"
          plain
          :disabled="ids.length === 0"
          @click="batchResponsiblePerson"
          >批量设定责任人</el-button
        >
        <!--        <el-button-->
        <!--          @click="-->
        <!--            useDownload(-->
        <!--              '/dmpDosPcm/psmparammonitorrule/export',-->
        <!--              '监控参数项',-->
        <!--              searchParam-->
        <!--            )-->
        <!--          "-->
        <!--        >-->
        <!--          <template #icon><i-ep-download /></template>导出</el-button-->
        <!--        >-->
        <el-dialog
          :close-on-click-modal="false"
          title="监控参数项数据导入"
          v-model="excelBox"
          width="555px"
          :key="uploadKey"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/dmpDosPcm/psmparammonitorrule/exportTemp',
                  '监控参数项数据上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              监控参数项数据上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              :disabled="uploadBtn"
              style="cursor: pointer"
              :loading="uploadLoading"
              @click="upload"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工段"
          prop="workshopSectionCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工序"
          prop="processName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ scope.row.processCode }}
          </template>
        </el-table-column>
        <el-table-column
          label="生产线"
          prop="processEquipCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="equipName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <!-- <el-table-column
          label="零件名称"
          prop="partName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        /> -->
        <el-table-column
          label="客户"
          prop="projectName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="型号描述"
          prop="productModelName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="产品型号"
          prop="productModel"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="程序名"
          prop="programName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="第一责任人"
          prop="responsiblePersonName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="是否启用"
          prop="enabled"
          width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag v-show="scope.row.enabled == 1" type="success">是</el-tag>
            <el-tag v-show="scope.row.enabled != 1" type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="110" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>

            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
              v-if="authAllPerm(['psm:jkcs:edit'])"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
              v-if="authAllPerm(['psm:jkcs:delete'])"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
              >
                <i-ep-delete />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <psmparammonitorrule-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <psmparammonitorrule-responsiblePerson
      :visible="responsiblePersonDialog.visible"
      :title="responsiblePersonDialog.title"
      :data="responsiblePersonDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="responsiblePersonDialog.readvisible"
      @change-visible="changeResponsiblePersonVisible"
    />
    <el-dialog
      :close-on-click-modal="false"
      title="监控参数项数据导入结果"
      v-model="resultVisible"
      width="555px"
    >
      <el-table
        ref="dataTableRef"
        :data="resultData"
        highlight-current-row
        border
        style="height: 600px"
      >
        <el-table-column
          label="序号"
          type="index"
          min-width="20"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="错误信息"
          prop="message"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDictionary,
  useDownload,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import _ from "lodash-es";
import { authAllPerm } from "@/utils/index";
// import SearchFormGroupPcm from "@/views/pcm/common/SearchFormGroupPcm.vue";

defineOptions({
  name: "PSMPSMPARAMMONITORRULE",
  inheritAttrs: false,
});

// --------------------------------------------------------------------------------------------------------组件 开始
// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  // 可执行字段相关的特定逻辑
};
// --------------------------------------------------------------------------------------------------------组件 结束

// 请求参数
const requestApi = "/dmpDosPcm/psmparammonitorrule/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  workshopSectionId: "",
  processId: "",
  equipCode: "",
  equipName: "",
  equipId: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  productModel: "",
  processEquipId: "",
  partName: "",
};

const deleteParam = {
  api: "/dmpDosPcm/psmparammonitorrule/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
  selections,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmparammonitorrule/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开工艺参数监控规则表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改监控参数项";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增监控参数项";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开工艺参数监控规则表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "监控参数项详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/dmpDosPcm/psmparammonitorrule/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

// 获取工序列表
const processCodeList: any = ref([]);
async function getProcessCodeList() {
  searchParam.value.processId = "";
  searchParam.value.processCode = "";
  processCodeList.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/dmpDosPcm/psmparammonitorrule/exist/process/options",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
    },
  });
  processCodeList.value = data;
}
function processChange() {
  getEquipList();
  getProjectList();
  getProductModelList();
  getProcessEquipList();
}
// 获取工序列表
const processEquipList: any = ref([]);
async function getProcessEquipList() {
  searchParam.value.processEquipId = "";
  processEquipList.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/dmpDosPcm/psmparammonitorrule/exist/processEquip/options",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
      processId: searchParam.value.processId,
    },
  });
  processEquipList.value = data;
}
function processEquipChange() {
  getEquipList();
  getProjectList();
  getProductModelList();
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id?: string) {
  searchParam.value.equipId = "";
  equipList.value = [];
  const res: any = await request({
    // url: "/iotadmin/scaequipinfo/getlist",
    // url: "/dmpDosPcm/equipmentInfo/getList",
    url: "/dmpDosPcm/psmparammonitorrule/exist/equip/options",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      processEquipId: searchParam.value.processEquipId,
    },
  });
  if (res.code === 200) {
    equipList.value = res.data;
  }
}
function equipChange() {
  getProjectList();
  getProductModelList();
}

// 获取项目列表
const projectList = ref([]);
const getProjectList = async () => {
  searchParam.value.projectId = "";
  projectList.value = [];
  await request({
    // url: `mdm/mdmprojectinfo/getList`,
    url: "/dmpDosPcm/psmparammonitorrule/exist/project/options",
    method: "post",
    data: {
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      equipIds: searchParam.value.equipId ? [searchParam.value.equipId] : [],
      processEquipId: searchParam.value.processEquipId,
    },
  }).then((res) => {
    projectList.value = res.data;
  });
};
// 改变项目列表
const changeProject = (e: string) => {
  productModelList.value = [];
  filteredOptions.value = [];
  searchParam.value.productModel = "";
  if (e) {
    const current = projectList.value?.filter((item) => item.id == e)[0] ?? {};
    searchParam.value.projectName = current.projectName;
    searchParam.value.projectCode = current.projectCode;
    getProductModelList(e);
  } else {
    searchParam.value.projectName = "";
    searchParam.value.projectCode = "";
    getProductModelList();
  }
};

// 根据项目获取产品型号
// 获取产品型号
const productModelList = ref<any>([]);
const filteredOptions = ref<any>([]);
const getProductModelList = async (id?: string) => {
  searchParam.value.productModel = "";
  productModelList.value = [];
  filteredOptions.value = [];
  filteredOptions1.value = [];
  await request({
    // url: "mdm/mdmproductinfo/getList",
    url: "/dmpDosPcm/psmparammonitorrule/exist/product/options",
    method: "post",
    data: {
      projectIds: searchParam.value.projectId
        ? [searchParam.value.projectId]
        : [],
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      equipIds: searchParam.value.equipId ? [searchParam.value.equipId] : [],
      processEquipId: searchParam.value.processEquipId,
    },
  }).then((res) => {
    productModelList.value = res.data;
    filteredOptions.value = [...productModelList.value];
    filteredOptions1.value = [...productModelList.value];
  });
};

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productModelList.value];
    return;
  }
  filteredOptions.value = productModelList.value.filter((option: any) =>
    option.productModel.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const filteredOptions1 = ref<any>([]);
const customFilter1 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions1.value = [...productModelList.value];
    return;
  }
  filteredOptions1.value = productModelList.value.filter((option: any) => {
    return option?.productModelName
      ?.toLowerCase()
      .includes(query.toLowerCase());
  });
}, 300); // 延迟 300ms

// const changeProductModel = (e: string) => {
//   if (e) {
//     productModelList.value.forEach((item: any) => {
//       if (item.productCode == e) {
//         formData.productModelName = item.productName;
//         formData.productModelCode = item.productCode;
//       }
//     });
//   } else {
//     formData.productModelName = "";
//     formData.productModelCode = "";
//     formData.productModel = "";
//   }
// };
onMounted(() => {
  getProcessCodeList();
  getEquipList();
  // 项目
  getProjectList();
  getProductModelList();
  getWorkshopSectionList();
  getProcessEquipList();
});

// 导入excel
const uploadApi = "/dmpDosPcm/psmparammonitorrule/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");
const resultVisible = ref(false);
const resultData = ref([]);
const uploadKey = ref(Math.random());

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

const uploadLoading = ref(false);

async function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }
  uploadLoading.value = true;
  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  try {
    await request
      .post(uploadApi, formdata, config)
      .then((res) => {
        ElMessage({
          type: "success",
          message: "上传成功！",
        });

        if (res.data && res.data.length > 0) {
          resultVisible.value = true;
          resultData.value = res.data.map((item) => ({ message: item }));
        }

        excelBox.value = false;
        uploadBtn.value = true;
        uploadKey.value = Math.random();
        search();
      })
      .catch((error) => {
        console.log(error);
      });
  } finally {
    uploadLoading.value = false;
  }
}
const resetHandle = () => {
  reset();
  getEquipList();
  getProductModelList();
  getProjectList();
  getProcessCodeList();
  getProcessEquipList();
};
const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
const changeWorkshopSection = () => {
  getProcessCodeList();
  getProcessEquipList();
  getEquipList();
  getProjectList();
  getProductModelList();
};

const deleteLoading = ref(false);

const exportExcel = () => {
  if (ids.length === 0) {
    ElMessage.warning("请勾选导出项");
    return;
  }

  ElMessageBox.confirm("确认导出已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    deleteLoading.value = true;
    useDownload(
      "/dmpDosPcm/psmparammonitorrule/exportExcel",
      "监控参数",
      ids.value
    )
      .then(() => {
        ElMessage.success("导出成功");
      })
      .finally(() => {
        deleteLoading.value = false;
      });
  });
};

const batchEnable = (enabled) => {
  if (ids.value.length === 0) {
    ElMessage.warning("请勾选数据项");
    return;
  }
  ElMessageBox.confirm(
    `确认${enabled ? "启用" : "停用"}已选中的数据项?`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    await request({
      url: `/dmpDosPcm/psmparammonitorrule/batchSaveEnable`,
      method: "post",
      data: {
        ids: ids.value,
        enabled,
      },
    });
    search();
  });
};

const responsiblePersonDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function changeResponsiblePersonVisible(value: boolean) {
  responsiblePersonDialog.visible = value;
  if (!value) {
    responsiblePersonDialog.data = {};
  }
}
const batchResponsiblePerson = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请勾选数据项");
    return;
  }
  const workshopSectionId = [
    ...new Set(selections.value.map((item) => item.workshopSectionId)),
  ];
  if (workshopSectionId.length > 1) {
    ElMessage.warning("请选择同一工段");
    return;
  }
  responsiblePersonDialog.title = "批量修改责任人";
  responsiblePersonDialog.visible = true;
  responsiblePersonDialog.readvisible = false;
  responsiblePersonDialog.data = {
    ids: ids.value,
    workshopSectionId: workshopSectionId[0],
  };
};
</script>
